//
//  GenderAlertView.swift
//  MT
//
//  Created by M on 2019/12/17.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory

class LocalGenderModel: NSObject {
    
    /// 可选类型
    @objc
    enum GenderType: Int {
        case male = 0
        case female
        case unknown
        
        /// 图片名称
        var imageName: String? {
            switch self {
            case .male:         return "icon_male"
            case .female:       return "icon_female"
            default:            return nil
            }
        }
        
        /// 标题
        var title: String {
            switch self {
            case .male:         return "只看男生"
            case .female:       return "只看女生"
            case .unknown:      return "不限"
            }
        }
        
        /// 请求
        var requestType: Int {
            switch self {
            case .male:         return 0
            case .female:       return 1
            default:            return -1
            }
        }
    }
    var genderType: GenderType

    /// 是否选中
    var isSelected: Bool = false
    
    init(genderType: GenderType) {
        self.genderType = genderType
        super.init()
    }
    
}

class GenderAlertView: BaseAlertView {
    
    /// 类型
    var types: [LocalGenderModel]
    
    /// Table View
    lazy var tableView: UITableView = {
        let tv = UITableView(frame: CGRect(x: 0, y: 18, width: self.frame.width, height: 172), style: .grouped)
        tv.backgroundColor = UIColor.common.x161616
        tv.separatorStyle = .none
        tv.rowHeight = 60
        tv.isScrollEnabled = false
        tv.bounces = false
        tv.delegate = self
        tv.dataSource = self
        tv.register(GenderAlertViewTableViewCell.self, forCellReuseIdentifier: String(describing: GenderAlertViewTableViewCell.self))
        return tv
    }()
    
    /// 性别回调 - 0: 男 1: 女
    typealias GenderSelectionCallBack = ((_: LocalGenderModel.GenderType) -> Swift.Void)

    var genderSelectionCallBack: GenderSelectionCallBack
    init(withSelectedGenderType type: LocalGenderModel.GenderType, selectedType: @escaping GenderSelectionCallBack) {
        self.genderSelectionCallBack = selectedType
        self.types = [LocalGenderModel(genderType: .female),
                      LocalGenderModel(genderType: .male),
                      LocalGenderModel(genderType: .unknown)]
        for t in types {
            if t.genderType == type { t.isSelected = true }
        }
        super.init(height: 280, popStyle: .bottom)
        setup()
        callBackSetup()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: ------------------ 初始化 ----------------------
extension GenderAlertView {
    
    private func setup() {
        backgroundCoverBackgroundColor = .clear
        title = "筛选"
        isDismissButtonHidden = true
//        set(text: "保存", color: .white, font: PingFangSCRegularFont(14))
        addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self)
            make.top.equalTo(titleLabel.snp.bottom).offset(10)
            make.height.equalTo(172)
        }
    }
    
    private func callBackSetup() {
        dismissCallBack = { [weak self] (view) in
            guard let weakSelf = self else { return }
            guard let currentSelectedType = (weakSelf.types.filter {
                return $0.isSelected
            }).first else { return }
            weakSelf.genderSelectionCallBack(currentSelectedType.genderType)
        }
    }
    
}

// MARK: ------------------ 所有代理 ----------------------
// MARK: ------------------ UITableViewDelegate ----------------------
extension GenderAlertView: UITableViewDelegate {
    
}

// MARK: ------------------ UITableViewDataSource ----------------------
extension GenderAlertView: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return types.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: GenderAlertViewTableViewCell.self), for: indexPath) as? GenderAlertViewTableViewCell else {
            return tableView.dequeueReusableCell(withIdentifier: String(describing: GenderAlertViewTableViewCell.self), for: indexPath)
        }
        cell.delegate = self
        cell.model = types[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}

// MARK: ------------------ GenderAlertViewTableViewCellDelegate ----------------------
extension GenderAlertView: GenderAlertViewTableViewCellDelegate {
    
    func alertViewTableViewCellDidClickButton(_ cell: GenderAlertViewTableViewCell) {
        for t in self.types {
            t.isSelected = t.genderType == cell.model?.genderType
        }
        tableView.reloadData()
        guard let currentSelectedType = (self.types.filter {
            return $0.isSelected
        }).first else { return }
        self.genderSelectionCallBack(currentSelectedType.genderType)
        dismiss(animated: isDismissAnimated, completion: nil)
    }
    
}

// MARK: ------------------ 代理方法 ----------------------
@objc
protocol GenderAlertViewTableViewCellDelegate: NSObjectProtocol {
    @objc optional func alertViewTableViewCellDidClickButton(_ cell: GenderAlertViewTableViewCell)
}

// MARK: ------------------ GenderAlertViewTableViewCell ----------------------
class GenderAlertViewTableViewCell: UITableViewCell {
    
    weak var delegate: GenderAlertViewTableViewCellDelegate?
    
    /// 性别模型
    var model: LocalGenderModel? {
        didSet {
            guard let model = model else { return }
            button.backgroundColor = model.isSelected ? UIColor.theme.main : UIColor.clear
            button.setTitle(model.genderType.title, for: .normal)
            button.layer.borderWidth = model.isSelected ? 0 : 1
            if let imageName = model.genderType.imageName {
                button.setImage(UIImage(named: imageName), for: .normal)
                button.setImage(UIImage(named: imageName + "_selected"), for: .selected)
                if let imageView = button.imageView { button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageView.frame.width, bottom: 0, right: imageView.frame.width) }
                if let titleLabel = button.titleLabel { button.imageEdgeInsets = UIEdgeInsets(top: 0, left: titleLabel.frame.width + 5, bottom: 0, right: -titleLabel.frame.width) }
            } else {
                button.setImage(nil, for: .normal)
            }
            button.isSelected = isSelected
        }
    }
    
    /// 按钮
    lazy var button: UIButton = {
        let btn = UIButton()
        btn.titleLabel?.font = PingFangSCRegularFont(16)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.setTitleColor(UIColor.text.x1d1a1a, for: .selected)
        btn.layer.cornerRadius = 22
        btn.layer.borderColor = UIColor.white.cgColor
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(genderAlertViewCell(didClickButton:)), for: .touchUpInside)
        return btn
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        initializeUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// UI 初始化
    private func initializeUI() {
        selectionStyle = .none
        self.contentView.backgroundColor = UIColor.common.x161616
        self.contentView.addSubview(button)
        button.snp.makeConstraints { (make) in
            make.center.equalTo(contentView)
            make.width.equalTo(210)
            make.height.equalTo(44)
        }
    }
    
    /// 设置是否选中
    public func setSeleted(_ isSelected: Bool) {
        button.isSelected = isSelected
        button.backgroundColor = isSelected ? UIColor.theme.main : UIColor.white
        button.layer.borderWidth = isSelected ? 0 : 1
    }
    
    /// 按钮点击
    @objc private func genderAlertViewCell(didClickButton sender: UIButton) {
        if let delegate = delegate {
            delegate.alertViewTableViewCellDidClickButton?(self)
        }
    }
    
}

